package com.juanpi.mkt.ruleengine.match;

import java.util.ArrayList;

import org.mvel2.MVEL;

import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPRuntime;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.juanpi.mkt.ruleengine.item.Fact;
import com.juanpi.mkt.ruleengine.item.Goods;
import com.juanpi.mkt.ruleengine.item.Rule;
import com.juanpi.mkt.ruleengine.item.RuleCondition;
import com.juanpi.mkt.ruleengine.item.User;

import example.model.Product;
import test.TestListener;

public class EPLRuleMatcher implements RuleMatcher{
	
	
	public boolean match(Fact fact,Rule rule)
	{
		
		
		boolean matchResult=false;
		
		
		ArrayList<RuleCondition> conditionList= rule.getConditionList();
		
		String patternExpression=rule.getConditionPattern();
		
		
		//match all rule condition separately ,put the conditon match reuslt to rule match patter
		for(RuleCondition con:conditionList)
		{
			RuleConditionMatcher conMactcher= RuleConditionMatcherFactory.getConditionMatcher(con.getType());
			boolean conditonMatchResult=conMactcher.match(fact, con);
			
			patternExpression=patternExpression.replaceFirst(con.getId(), String.valueOf(conditonMatchResult));
			
		}
		
		//match the rule with rule pattern
		
		matchResult = (Boolean) MVEL.eval(patternExpression);  
		
		
		System.out.println(matchResult);
			
		
		return matchResult;
	}
	
	
	
	
	
	
	public static void main(String[] args) {
		
		EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();

		EPAdministrator admin = epService.getEPAdministrator();

//		String product = Product.class.getName();
		//		String epl1 = "select * from " + product + ".win:time_batch(10 sec)";
		String epl1 = "select sum(price) from " + product + ".win:length_batch(2)";

		EPStatement state = admin.createEPL(epl1);
		state.addListener(new TestListener());

		EPRuntime runtime = epService.getEPRuntime();

		Product esb = new Product();
		esb.setPrice(1);
		esb.setType("esb");
		runtime.sendEvent(esb);
		
//		
//		System.out.println(String.valueOf(true));
//		
//		String tes="totalAmontMorethan200 and totalCountsMorethan2 ";
//		
//		System.out.println(tes.replaceFirst("totalAmontMorethan200",String.valueOf(true)));
		
		Fact cartFact=new Fact();
		
		User u=new User(1,1,"testuser");//id 
		cartFact.setUser(u);
		
		Goods niketshirt=new Goods(1,11,110,"nike");
		Goods nikeshoes=new Goods(2,12,220,"nike");
		Goods adtshirt=new Goods(3,11,120,"ad");
		Goods adshoes=new Goods(4,12,230,"ad");
		
		cartFact.addGoods(nikeshoes);
		cartFact.addGoods(niketshirt);
		cartFact.addGoods(adtshirt);
		cartFact.addGoods(adshoes);
		
		
		System.out.println(MVEL.eval("user.type ",cartFact));  
		
	}

}
